<template>
  <div class="platform-page">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" label-width="80px">
        <el-form-item label="站台名称">
          <el-input
            v-model="searchForm.platformName"
            placeholder="请输入站台名称"
            clearable
            style="width: 260px"
          />
        </el-form-item>
        <el-form-item label="选择仓库">
          <el-select
            v-model="searchForm.warehouseId"
            placeholder="请选择"
            filterable
            clearable
            style="width: 260px"
            :loading="warehouseLoading"
          >
            <el-option
              v-for="item in warehouseOptions"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表区域 -->
    <el-card class="table-card">
      <div style="margin-bottom: 10px;">
        <el-button type="primary" @click="openDialog">添加</el-button>
        <el-button type="danger" :disabled="multipleSelection.length === 0" @click="handleBatchDelete">
          删除
        </el-button>
      </div>
      <el-table
        :data="tableData"
        row-key="platformId"
        style="width: 100%"
        v-loading="loading"
        height="350px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" fixed="left" />
        <el-table-column fixed="left" type="index" label="序号" width="60" />
        <el-table-column prop="platformName" label="站台名称" width="150" />
        <el-table-column prop="platformCode" label="站台编码" width="120" />
        <el-table-column prop="deviceCode" label="设备编码" width="120" />
        <el-table-column prop="warehouseName" label="所属库房" width="200" />
        <el-table-column prop="platformType" label="站台类型" width="120" />
        <el-table-column prop="functionType" label="功能类型" width="120" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.platformState === 1 ? 'success' : 'danger'">
              {{ row.platformState === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createrTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createrTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="createor" label="创建人" width="120" />
        <el-table-column label="操作" fixed="right" width="280">
          <template #default="{ row }">
            <el-button link size="small" type="primary" @click="openEditDialog(row)">编辑</el-button>
            <el-button link size="small" type="info" @click="openDetailDialog(row)">查看</el-button>
            <el-button link size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            <el-button link size="small" type="warning" >货品明细</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页 -->
    <el-card class="action-card">
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pageinfo.pageIndex"
          v-model:page-size="pageinfo.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="pageinfo.total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑/详情站台弹框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogMode === 'add' ? '添加站台' : dialogMode === 'edit' ? '编辑站台' : '站台详情'" 
      width="700px" 
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="站台名称" prop="platformName">
              <el-input 
                v-model="form.platformName" 
                placeholder="请输入站台名称" 
                clearable 
                :disabled="dialogMode === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站台编码" prop="platformCode">
              <el-input 
                v-model="form.platformCode" 
                :placeholder="dialogMode === 'add' ? '点击自动生成按钮获取编号' : '站台编码不可修改'" 
                :readonly="dialogMode === 'add' || dialogMode === 'edit'"
                :disabled="dialogMode === 'detail'"
              >
                <template #append v-if="dialogMode === 'add'">
                  <el-button @click="generatePlatformCode" :loading="generatingCode">自动生成</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属库房" prop="warehouseId">
              <el-select
                v-model="form.warehouseId"
                placeholder="请选择"
                filterable
                clearable
                style="width: 100%"
                :loading="warehouseLoading"
                :disabled="dialogMode === 'detail'"
              >
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.warehouseId"
                  :label="item.warehouseName"
                  :value="item.warehouseId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编码">
              <el-input 
                v-model="form.deviceCode" 
                :placeholder="dialogMode === 'add' ? '点击自动生成按钮获取编号' : '设备编码不可修改'" 
                :readonly="dialogMode === 'add' || dialogMode === 'edit'"
                :disabled="dialogMode === 'detail'"
              >
                <template #append v-if="dialogMode === 'add'">
                  <el-button @click="generateDeviceCode" :loading="generatingDeviceCode">自动生成</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="站台类型" prop="platformTypeId">
              <el-select
                v-model="form.platformTypeId"
                placeholder="请选择"
                filterable
                clearable
                style="width: 100%"
                :loading="platformTypeLoading"
                :disabled="dialogMode === 'detail'"
              >
                <el-option
                  v-for="item in platformTypeOptions"
                  :key="item.dictionaryId"
                  :label="item.dictionaryName"
                  :value="item.dictionaryId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="功能类型" prop="functionId">
              <el-select
                v-model="form.functionId"
                placeholder="请选择"
                filterable
                clearable
                style="width: 100%"
                :loading="functionTypeLoading"
                :disabled="dialogMode === 'detail'"
              >
                <el-option
                  v-for="item in functionTypeOptions"
                  :key="item.dictionaryId"
                  :label="item.dictionaryName"
                  :value="item.dictionaryId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="platformState">
              <el-radio-group v-model="form.platformState" :disabled="dialogMode === 'detail'">
                <el-radio :value="1">启用</el-radio>
                <el-radio :value="2">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在楼层">
              <el-input-number 
                v-model="form.floorId" 
                :min="0" 
                style="width: 100%" 
                placeholder="请输入所在楼层"
                :disabled="dialogMode === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="排序号" prop="platformOrderBy">
          <el-input-number 
            v-model="form.platformOrderBy" 
            :min="0" 
            style="width: 100%" 
            :disabled="dialogMode === 'detail'"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.platformDesc"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            maxlength="500"
            show-word-limit
            :disabled="dialogMode === 'detail'"
          />
        </el-form-item>
        <el-form-item v-if="dialogMode === 'detail'" label="创建人">
          <el-input v-model="form.createor" readonly />
        </el-form-item>
        <el-form-item v-if="dialogMode === 'detail'" label="创建时间">
          <el-input :value="formatDate(form.createrTime)" readonly />
        </el-form-item>
        <el-form-item v-if="dialogMode === 'detail' && form.updater" label="修改人">
          <el-input v-model="form.updater" readonly />
        </el-form-item>
        <el-form-item v-if="dialogMode === 'detail' && form.updateTime" label="修改时间">
          <el-input :value="formatDate(form.updateTime)" readonly />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            v-if="dialogMode !== 'detail'" 
            type="primary" 
            @click="handleSave" 
            :loading="saving"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import myaxios from '@/http/MyAxios'

// 查询条件
const searchForm = reactive({
  platformName: '', // 站台名称（模糊查询）
  warehouseId: null as number | null, // 所属仓库（精确查询）
})

// 分页信息
const pageinfo = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

// 列表数据
const tableData = ref<any[]>([])
const loading = ref(false)
const multipleSelection = ref<any[]>([])

// 仓库选项
const warehouseOptions = ref<Array<{ warehouseId: number; warehouseName: string }>>([])
const warehouseLoading = ref(false)

// 弹框相关
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const saving = ref(false)
const dialogMode = ref<'add' | 'edit' | 'detail'>('add') // 弹框模式：新增、编辑、详情

// 表单数据
const form = reactive({
  platformId: null as number | null,
  platformName: '',
  platformCode: '',
  deviceCode: '',
  warehouseId: null as number | null,
  platformTypeId: null as number | null,
  functionId: null as number | null,
  platformState: 1, // 默认启用
  floorId: null as number | null,
  platformOrderBy: 2, // 默认排序号2
  platformDesc: '',
  createor: '',
  createrTime: null as Date | string | null,
  updater: '',
  updateTime: null as Date | string | null,
})

// 表单验证规则
const rules: FormRules = {
  platformName: [{ required: true, message: '请输入站台名称', trigger: 'blur' }],
  platformCode: [{ required: true, message: '请输入站台编码', trigger: 'blur' }],
  warehouseId: [{ required: true, message: '请选择所属库房', trigger: 'change' }],
  platformTypeId: [{ required: true, message: '请选择站台类型', trigger: 'change' }],
  functionId: [{ required: true, message: '请选择功能类型', trigger: 'change' }],
  platformState: [{ required: true, message: '请选择状态', trigger: 'change' }],
  platformOrderBy: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
}

// 站台类型选项
const platformTypeOptions = ref<Array<{ dictionaryId: number; dictionaryName: string }>>([])
const platformTypeLoading = ref(false)

// 功能类型选项
const functionTypeOptions = ref<Array<{ dictionaryId: number; dictionaryName: string }>>([])
const functionTypeLoading = ref(false)

// 编号生成相关
const generatingCode = ref(false)
const generatingDeviceCode = ref(false)

const formatDate = (val?: string | Date | null) => {
  if (!val) return '-'
  return dayjs(val).format('YYYY-MM-DD HH:mm:ss')
}

// 判断是否为根字典（父级id为0或null）
const isRootDictionary = (item: any) => {
  return !item?.dictionaryParentId || item.dictionaryParentId === 0 || item.dictionaryParentId === '0' || item.dictionaryParentId === null
}

// 匹配字典项
const matchDictionary = (item: any, names: string[], codes: string[]) => {
  const name = (item?.dictionaryName || '').toLowerCase()
  const code = (item?.dictionaryCode || '').toLowerCase()
  return names.some(n => name === n.toLowerCase() || name.includes(n.toLowerCase())) ||
    codes.some(c => code === c.toLowerCase())
}

// 查找父级字典ID
const findDictionaryParentId = async (nameCandidates: string[], codeCandidates: string[]) => {
  const params = { Pageindex: 1, PageSize: 1000 }
  try {
    const res = await myaxios.get('/api/Dictionary/GetDictionaryList', { params })
    const list = res.data?.data?.data || []
    const found = list.find((item: any) => isRootDictionary(item) && matchDictionary(item, nameCandidates, codeCandidates))
    if (found?.dictionaryId) return found.dictionaryId
  } catch (error) {
    console.warn('获取字典列表失败', error)
  }

  for (const name of nameCandidates) {
    try {
      const res = await myaxios.get('/api/Dictionary/GetDictionaryList', {
        params: { DictionaryName: name, Pageindex: 1, PageSize: 200 }
      })
      const list = res.data?.data?.data || []
      const found = list.find((item: any) => isRootDictionary(item))
      if (found?.dictionaryId) return found.dictionaryId
    } catch (error) {
      console.warn(`按名称 ${name} 获取字典失败`, error)
    }
  }
  return null
}

// 获取字典子项
const fetchDictionaryChildren = async (parentId: string | number | null) => {
  if (!parentId) return []
  try {
    const res = await myaxios.get('/api/Dictionary/GetDictionaryChildren', {
      params: { ParentId: parentId, Pageindex: 1, PageSize: 1000 }
    })
    return res.data?.data?.data || []
  } catch (error) {
    console.warn('获取字典子项失败', error)
    return []
  }
}

// 加载站台类型列表
const loadPlatformTypeList = async () => {
  if (platformTypeLoading.value) return
  platformTypeLoading.value = true
  try {
    const parentId = await findDictionaryParentId(['站台类型'], ['platformtype', 'platform_type'])
    if (!parentId) {
      ElMessage.warning('未找到站台类型字典，请先配置字典')
      return
    }
    const children = await fetchDictionaryChildren(parentId)
    platformTypeOptions.value = children.map((item: any) => ({
      dictionaryId: item.dictionaryId,
      dictionaryName: item.dictionaryName
    }))
  } catch (error) {
    console.error('加载站台类型列表失败:', error)
    ElMessage.error('加载站台类型列表失败，请稍后重试')
  } finally {
    platformTypeLoading.value = false
  }
}

// 加载功能类型列表
const loadFunctionTypeList = async () => {
  if (functionTypeLoading.value) return
  functionTypeLoading.value = true
  try {
    const parentId = await findDictionaryParentId(['站台功能', '功能类型'], ['platformfunction', 'platform_function', 'functiontype', 'function_type'])
    if (!parentId) {
      ElMessage.warning('未找到站台功能字典，请先配置字典')
      return
    }
    const children = await fetchDictionaryChildren(parentId)
    functionTypeOptions.value = children.map((item: any) => ({
      dictionaryId: item.dictionaryId,
      dictionaryName: item.dictionaryName
    }))
  } catch (error) {
    console.error('加载功能类型列表失败:', error)
    ElMessage.error('加载功能类型列表失败，请稍后重试')
  } finally {
    functionTypeLoading.value = false
  }
}

// 加载仓库列表（复用GetDrift页面的逻辑）
const loadWarehouses = async () => {
  if (warehouseLoading.value) return
  warehouseLoading.value = true
  try {
    const res = await myaxios({
      url: '/api/Warehousing/GetWarehouse',
      method: 'get',
    })
    if (res.data?.code === 200 || res.data?.success) {
      const warehouses = res.data.data || []
      warehouseOptions.value = warehouses.map((item: any) => ({
        warehouseId: item.warehouseId,
        warehouseName: item.warehouseName,
      }))
    } else {
      ElMessage.error(res.data?.message || '获取仓库列表失败')
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败，请稍后重试')
  } finally {
    warehouseLoading.value = false
  }
}

// 获取站台列表（分页）
const getPlatformList = () => {
  loading.value = true
  myaxios({
    url: '/api/Platform/GetPlatformPage',
    method: 'get',
    params: {
      Pageindex: pageinfo.pageIndex,
      PageSize: pageinfo.pageSize,
      platformName: searchForm.platformName,
      warehouseId: searchForm.warehouseId,
    },
  })
    .then(res => {
      const data = res.data?.data
      // 后端分页结构：data.data 为列表，data.listCount 为总数
      tableData.value = data?.data || []
      pageinfo.total = data?.listCount || 0
    })
    .catch(err => {
      console.error('获取站台列表失败:', err)
      ElMessage.error('获取站台列表失败')
    })
    .finally(() => {
      loading.value = false
    })
}

// 查询
const handleSearch = () => {
  pageinfo.pageIndex = 1
  getPlatformList()
}

// 重置
const handleReset = () => {
  searchForm.platformName = ''
  searchForm.warehouseId = null
  pageinfo.pageIndex = 1
  getPlatformList()
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection
}

// 分页尺寸变化
const handleSizeChange = (val: number) => {
  pageinfo.pageSize = val
  pageinfo.pageIndex = 1
  getPlatformList()
}

// 页码变化
const handleCurrentChange = (val: number) => {
  pageinfo.pageIndex = val
  getPlatformList()
}

// 打开新增弹框
const openDialog = () => {
  dialogMode.value = 'add'
  resetForm()
  loadWarehouses()
  loadPlatformTypeList()
  loadFunctionTypeList()
  dialogVisible.value = true
}

// 打开编辑弹框
const openEditDialog = async (row: any) => {
  dialogMode.value = 'edit'
  resetForm()
  loadWarehouses()
  loadPlatformTypeList()
  loadFunctionTypeList()
  
  // 加载站台详情
  try {
    const res = await myaxios({
      url: `/api/Platform/GetPlatformDetail`,
      method: 'get',
      params: { platformId: row.platformId },
    })
    
    if (res.data?.code === 200 && res.data?.data) {
      const data = res.data.data
      form.platformId = data.platformId
      form.platformName = data.platformName || ''
      form.platformCode = data.platformCode || ''
      form.deviceCode = data.deviceCode || ''
      form.warehouseId = data.warehouseId || null
      form.platformTypeId = data.platformTypeId || null
      form.functionId = data.functionId || null
      form.platformState = data.platformState || 1
      form.floorId = data.floorId || null
      form.platformOrderBy = data.platformOrderBy || 0
      form.platformDesc = data.platformDesc || ''
    } else {
      ElMessage.error(res.data?.message || '获取站台详情失败')
      return
    }
  } catch (error: any) {
    console.error('获取站台详情失败:', error)
    ElMessage.error('获取站台详情失败，请稍后重试')
    return
  }
  
  dialogVisible.value = true
}

// 打开详情弹框
const openDetailDialog = async (row: any) => {
  dialogMode.value = 'detail'
  resetForm()
  loadWarehouses()
  loadPlatformTypeList()
  loadFunctionTypeList()
  
  // 加载站台详情
  try {
    const res = await myaxios({
      url: `/api/Platform/GetPlatformDetail`,
      method: 'get',
      params: { platformId: row.platformId },
    })
    
    if (res.data?.code === 200 && res.data?.data) {
      const data = res.data.data
      form.platformId = data.platformId
      form.platformName = data.platformName || ''
      form.platformCode = data.platformCode || ''
      form.deviceCode = data.deviceCode || ''
      form.warehouseId = data.warehouseId || null
      form.platformTypeId = data.platformTypeId || null
      form.functionId = data.functionId || null
      form.platformState = data.platformState || 1
      form.floorId = data.floorId || null
      form.platformOrderBy = data.platformOrderBy || 0
      form.platformDesc = data.platformDesc || ''
      form.createor = data.createor || ''
      form.createrTime = data.createrTime || null
      form.updater = data.updater || ''
      form.updateTime = data.updateTime || null
    } else {
      ElMessage.error(res.data?.message || '获取站台详情失败')
      return
    }
  } catch (error: any) {
    console.error('获取站台详情失败:', error)
    ElMessage.error('获取站台详情失败，请稍后重试')
    return
  }
  
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  form.platformId = null
  form.platformName = ''
  form.platformCode = '' // 重置为空，等待自动生成
  form.deviceCode = '' // 重置为空，等待自动生成
  form.warehouseId = null
  form.platformTypeId = null
  form.functionId = null
  form.platformState = 1
  form.floorId = null
  form.platformOrderBy = 2
  form.platformDesc = ''
  form.createor = ''
  form.createrTime = null
  form.updater = ''
  form.updateTime = null
  formRef.value?.clearValidate()
}

// 编号生成相关函数
const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
  const now = new Date()
  const segments = (rule?.timeRule || '')
    .split(',')
    .map((s: string) => s.trim().toUpperCase())
    .filter(Boolean)
    .sort((a: string, b: string) => {
      const indexA = TIME_SEGMENT_ORDER.indexOf(a)
      const indexB = TIME_SEGMENT_ORDER.indexOf(b)
      if (indexA === -1 && indexB === -1) return 0
      if (indexA === -1) return 1
      if (indexB === -1) return -1
      return indexA - indexB
    })
  const datePart = segments
    .map((seg: string) => {
      switch (seg) {
        case 'YYYY': return String(now.getFullYear())
        case 'YY': return String(now.getFullYear()).slice(-2)
        case 'MM': return pad(now.getMonth() + 1)
        case 'DD': return pad(now.getDate())
        case 'HH': return pad(now.getHours())
        case 'MI': return pad(now.getMinutes())
        case 'SS': return pad(now.getSeconds())
        default: return ''
      }
    })
    .join('')
  const seq = '1'.padStart(rule?.serialLength || 3, '0')
  return `${rule?.codePrefix || ''}${datePart}${seq}`
}

const requestPlatformCode = async () => {
  try {
    const res = await myaxios.get('/api/Number/GenerateNumber', {
      params: { targetCode: 'Platform', targetName: '站台' }
    })
    if (res?.data?.code === 200 && res?.data?.data) {
      return String(res.data.data)
    }
    throw new Error(res?.data?.message || '生成编号失败')
  } catch (err) {
    console.warn('[platform] GenerateNumber 接口不可用，尝试规则生成', err)
    const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
      params: { targetCode: 'Platform', targetName: '站台' }
    })
    const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
    if (list.length > 0) {
      return buildCodeFromRule(list[0])
    }
    throw new Error('未找到对应的编号规则，请先配置编号规则')
  }
}

const generatePlatformCode = async () => {
  generatingCode.value = true
  try {
    form.platformCode = await requestPlatformCode()
    ElMessage.success('编号生成成功')
  } catch (err: any) {
    ElMessage.error(err?.message || '生成编号失败')
  } finally {
    generatingCode.value = false
  }
}

// 设备编码生成相关函数
const requestDeviceCode = async () => {
  try {
    const res = await myaxios.get('/api/Number/GenerateNumber', {
      params: { targetCode: 'Device', targetName: '设备' }
    })
    if (res?.data?.code === 200 && res?.data?.data) {
      return String(res.data.data)
    }
    throw new Error(res?.data?.message || '生成编号失败')
  } catch (err) {
    console.warn('[device] GenerateNumber 接口不可用，尝试规则生成', err)
    const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
      params: { targetCode: 'Device', targetName: '设备' }
    })
    const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
    if (list.length > 0) {
      return buildCodeFromRule(list[0])
    }
    throw new Error('未找到对应的编号规则，请先配置编号规则')
  }
}

const generateDeviceCode = async () => {
  generatingDeviceCode.value = true
  try {
    form.deviceCode = await requestDeviceCode()
    ElMessage.success('设备编码生成成功')
  } catch (err: any) {
    ElMessage.error(err?.message || '生成设备编码失败')
  } finally {
    generatingDeviceCode.value = false
  }
}

// 保存站台（新增）
const handleSave = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return

  // 新增模式下，如果用户没有输入站台编码，自动生成
  if (dialogMode.value === 'add' && !form.platformCode) {
    try {
      await generatePlatformCode()
      // 如果生成失败，停止保存
      if (!form.platformCode) {
        ElMessage.warning('请先生成站台编码')
        return
      }
    } catch (error) {
      ElMessage.warning('生成站台编码失败，请稍后重试')
      return
    }
  }

  // 新增模式下，如果用户没有输入设备编码，自动生成
  if (dialogMode.value === 'add' && !form.deviceCode) {
    try {
      await generateDeviceCode()
      // 如果生成失败，继续保存（设备编码不是必填字段）
      if (!form.deviceCode) {
        console.warn('设备编码生成失败，但继续保存')
      }
    } catch (error) {
      console.warn('生成设备编码失败，但继续保存', error)
      // 设备编码不是必填，生成失败也继续保存
    }
  }

  saving.value = true
  try {
    const url = dialogMode.value === 'add' ? '/api/Platform/CreatePlatform' : '/api/Platform/UpdatePlatform'
    const data: any = {
      platformName: form.platformName,
      warehouseId: form.warehouseId,
      platformTypeId: form.platformTypeId,
      functionId: form.functionId,
      functionState: form.platformState,
      floorId: form.floorId || 0,
      platformOrderBy: form.platformOrderBy,
      platformDesc: form.platformDesc || '',
    }

    // 编辑模式下，需要包含platformId，但不发送编码字段（因为后端不会更新编码）
    if (dialogMode.value === 'edit') {
      data.platformId = form.platformId
      // 编辑模式下，即使发送编码字段，后端也不会更新，但为了安全起见，我们仍然发送原始编码
      data.platformCode = form.platformCode || ''
      data.platformDevice = form.deviceCode || ''
    } else {
      // 新增模式下，必须包含编码字段
      data.platformCode = form.platformCode
      data.platformDevice = form.deviceCode || ''
    }

    const res = await myaxios({
      url,
      method: 'post',
      data,
    })

    if (res.data?.code === 200) {
      ElMessage.success(res.data?.message || (dialogMode.value === 'add' ? '添加站台成功' : '更新站台成功'))
      dialogVisible.value = false
      getPlatformList()
    } else {
      ElMessage.error(res.data?.message || (dialogMode.value === 'add' ? '添加站台失败' : '更新站台失败'))
    }
  } catch (error: any) {
    console.error(`${dialogMode.value === 'add' ? '添加' : '更新'}站台失败:`, error)
    const errorMsg =
      error?.response?.data?.message ||
      error?.message ||
      `${dialogMode.value === 'add' ? '添加' : '更新'}站台失败，请稍后重试`
    ElMessage.error(errorMsg)
  } finally {
    saving.value = false
  }
}

// 单个删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    '确认删除这条站台信息吗？',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      myaxios({
        url: '/api/Platform/DeletePlatform',
        method: 'delete',
        params: { platformId: row.platformId },
      })
        .then(res => {
          if (res.data?.code === 200) {
            ElMessage.success(res.data?.message || '删除成功')
            getPlatformList()
          } else {
            ElMessage.error(res.data?.message || '删除失败')
          }
        })
        .catch(error => {
          console.error('删除站台失败:', error)
          ElMessage.error('删除站台失败，请稍后重试')
        })
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 批量删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的站台')
    return
  }

  ElMessageBox.confirm(
    `确认删除选中的 ${multipleSelection.value.length} 条站台信息吗？`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const ids = multipleSelection.value.map(item => item.platformId)
      myaxios({
        url: '/api/Platform/DeletePlatforms',
        method: 'post',
        data: { ids },
      })
        .then(res => {
          if (res.data?.code === 200) {
            ElMessage.success(res.data?.message || '批量删除成功')
            multipleSelection.value = []
            getPlatformList()
          } else {
            ElMessage.error(res.data?.message || '批量删除失败')
          }
        })
        .catch(error => {
          console.error('批量删除站台失败:', error)
          ElMessage.error('批量删除站台失败，请稍后重试')
        })
    })
    .catch(() => {
      // 用户取消删除
    })
}

onMounted(() => {
  loadWarehouses()
  getPlatformList()
})
</script>

<style scoped>
.platform-page {
  padding: 10px;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 15px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>

